<template>
  <div class="personal-center">
    <div class="container">
      <div class="personal-layout">
        <!-- 左侧导航菜单 -->
        <div class="sidebar">
          <div class="user-card">
            <div class="avatar-wrapper">
              <el-avatar :size="80" :src="userInfo.avatar ? getFullAvatarURL(userInfo.avatar) : '/images/default-avatar.png'">
                <!-- 移除内嵌的img标签，让el-avatar组件正确显示头像 -->
              </el-avatar>
            </div>
            <div class="user-info">
              <h3 class="username">{{ userInfo.nickname || userInfo.username }}</h3>
              <p class="user-role">{{ getRoleText(userInfo.role) }}</p>
            </div>
            <div class="card-action">
              <el-button type="primary" plain size="small" @click="activeTab = 'account'">
                <el-icon><setting /></el-icon>
                设置
              </el-button>
            </div>
          </div>
          
          <el-menu
            :default-active="activeTab"
            class="side-menu"
            @select="handleMenuSelect"
          >
            <!-- 只对求职者显示的菜单项 -->
            <template v-if="userInfo.role === 'jobseeker'">
              <el-menu-item index="overview">
                <el-icon><data-board /></el-icon>
                <span>个人概览</span>
              </el-menu-item>
              
              <el-menu-item index="applications">
                <el-icon><document /></el-icon>
                <span>求职管理</span>
                <el-badge :value="4" class="menu-badge" v-if="false" />
              </el-menu-item>
              
              <el-menu-item index="resumes">
                <el-icon><files /></el-icon>
                <span>简历管理</span>
              </el-menu-item>
            </template>
            
            <!-- 所有用户都显示的菜单项 -->
            <el-menu-item index="account">
              <el-icon><user /></el-icon>
              <span>账号设置</span>
            </el-menu-item>
          </el-menu>
        </div>
        
        <!-- 右侧内容区域 -->
        <div class="content">
          <!-- 只对求职者显示的内容 -->
          <template v-if="userInfo.role === 'jobseeker'">
            <!-- 个人概览 -->
            <personal-overview v-if="activeTab === 'overview'" />
            
            <!-- 求职管理 -->
            <job-applications v-if="activeTab === 'applications'" />
            
            <!-- 简历管理 -->
            <div v-if="activeTab === 'resumes'" class="redirect-hint">
              <el-result
                icon="info"
                title="简历管理"
                sub-title="您可以在简历管理页面查看和编辑您的所有简历"
              >
                <template #extra>
                  <el-button type="primary" @click="goToResumes">前往简历管理</el-button>
                </template>
              </el-result>
            </div>
          </template>
          
          <!-- 收藏职位 -->
          <favorite-jobs v-if="activeTab === 'favorites'" />
          
          <!-- 消息通知 -->
          <message-center v-if="activeTab === 'messages'" />
          
          <!-- 账号设置 -->
          <account-settings v-if="activeTab === 'account'" />
          
          <!-- 非求职者且尝试访问求职者专用功能时显示提示 -->
          <el-result
            v-if="userInfo.role !== 'jobseeker' && ['overview', 'applications', 'resumes'].includes(activeTab)"
            icon="warning"
            title="访问受限"
            sub-title="该功能仅对求职者开放"
          >
            <template #extra>
              <el-button type="primary" @click="activeTab = 'account'">返回账号设置</el-button>
            </template>
          </el-result>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import {
  Setting,
  DataBoard,
  Document,
  Star,
  Files,
  ChatDotRound,
  User
} from '@element-plus/icons-vue'
import PersonalOverview from '@/components/personal/PersonalOverview.vue'
import JobApplications from '@/components/personal/JobApplications.vue'
import FavoriteJobs from '@/components/personal/FavoriteJobs.vue'
import MessageCenter from '@/components/personal/MessageCenter.vue'
import AccountSettings from '@/components/personal/AccountSettings.vue'
import { ElMessage } from 'element-plus'
import { getFullAvatarURL } from '@/utils/common'
import { getUserInfo } from '@/api/user'

const router = useRouter()

// 当前活动标签页
const activeTab = ref('overview')

// 用户信息
const userInfo = ref({
  id: '1001',
  username: 'zhangsan',
  nickname: '张三',
  avatar: '',
  role: 'jobseeker',
  email: 'zhangsan@example.com',
  phone: '13912345678',
  lastLogin: '2023-05-10 14:30:45'
})

// 角色文本映射
const getRoleText = (role) => {
  const roleMap = {
    'jobseeker': '求职者',
    'recruiter': '招聘者',
    'admin': '管理员'
  }
  return roleMap[role] || '用户'
}

// 菜单选择处理
const handleMenuSelect = (index) => {
  activeTab.value = index
}

// 前往简历管理页面
const goToResumes = () => {
  router.push('/seeker/resumes')
}

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    // 尝试使用API获取最新用户信息
    try {
      const response = await getUserInfo();
      if (response && response.code === 200 && response.data) {
        const userData = response.data;
        
        // 角色ID到角色名映射 - 修正为正确的映射关系
        const roleMap = {
          0: 'jobseeker', // 求职者
          1: 'recruiter', // 招聘者
          2: 'admin'      // 管理员
        }
        
        userInfo.value = {
          id: userData.id,
          username: userData.username,
          nickname: userData.realName || userData.username,
          avatar: userData.avatar || '', // 从API响应中获取头像URL
          role: roleMap[userData.role] || 'jobseeker',
          email: userData.email,
          phone: userData.phone || '',
          lastLogin: userData.lastLoginTime || new Date().toLocaleString()
        }
        
        // 更新localStorage中的用户信息
        localStorage.setItem('user', JSON.stringify(userData));
        return;
      }
    } catch (apiError) {
      console.error('API获取用户信息失败，尝试从本地存储获取', apiError);
    }
    
    // 如果API请求失败，从本地存储获取用户信息
    const userStr = localStorage.getItem('user')
    if (userStr) {
      const user = JSON.parse(userStr)
      
      // 角色ID到角色名映射 - 修正为正确的映射关系
      const roleMap = {
        0: 'jobseeker', // 求职者
        1: 'recruiter', // 招聘者
        2: 'admin'      // 管理员
      }
      
      userInfo.value = {
        id: user.id,
        username: user.username,
        nickname: user.realName || user.username,
        avatar: user.avatar || '', // 正确从localStorage中读取avatar字段
        role: roleMap[user.role] || 'jobseeker',
        email: user.email,
        phone: user.phone || '',
        lastLogin: user.lastLoginTime || new Date().toLocaleString()
      }
    } else {
      // 如果本地存储没有用户信息，跳转到登录页面
      router.push('/auth/login')
    }
  } catch (error) {
    console.error('获取用户信息失败', error)
    ElMessage.error('获取用户信息失败')
  }
}

// 初始化
onMounted(() => {
  fetchUserInfo().then(() => {
    // 非求职者用户默认显示账号设置页面
    if (userInfo.value.role !== 'jobseeker') {
      activeTab.value = 'account'
    }
    
    // 尝试从URL参数获取活动标签
    const tab = router.currentRoute.value.query.tab
    if (tab && ['overview', 'applications', 'favorites', 'resumes', 'messages', 'account'].includes(tab)) {
      // 如果尝试访问求职者专用标签且不是求职者，则重定向到账号设置
      if (userInfo.value.role !== 'jobseeker' && ['overview', 'applications', 'resumes'].includes(tab)) {
        activeTab.value = 'account'
      } else {
        activeTab.value = tab
      }
    }
  })
})
</script>

<style lang="scss" scoped>
@import '@/assets/styles/variables.css';

.personal-center {
  padding: var(--spacing-xl) 0;
  
  .personal-layout {
    display: flex;
    gap: var(--spacing-xl);
    
    .sidebar {
      width: 260px;
      flex-shrink: 0;
      
      .user-card {
        background-color: #fff;
        border-radius: var(--border-radius);
        padding: var(--spacing-lg);
        margin-bottom: var(--spacing-lg);
        box-shadow: var(--box-shadow);
        text-align: center;
        
        .avatar-wrapper {
          margin-bottom: var(--spacing-md);
        }
        
        .user-info {
          margin-bottom: var(--spacing-md);
          
          .username {
            font-size: 1.2rem;
            font-weight: 600;
            margin: 0 0 var(--spacing-xs);
            color: var(--text-primary);
          }
          
          .user-role {
            color: var(--text-secondary);
            margin: 0;
            font-size: 0.9rem;
          }
        }
      }
      
      .side-menu {
        border-radius: var(--border-radius);
        box-shadow: var(--box-shadow);
        
        .menu-badge {
          margin-left: var(--spacing-sm);
        }
      }
    }
    
    .content {
      flex-grow: 1;
      background-color: #fff;
      border-radius: var(--border-radius);
      padding: var(--spacing-lg);
      box-shadow: var(--box-shadow);
      min-height: 500px;
      
      .redirect-hint {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100%;
      }
    }
  }
}

// 响应式适配
@media (max-width: 768px) {
  .personal-layout {
    flex-direction: column;
    
    .sidebar {
      width: 100% !important;
      margin-bottom: var(--spacing-lg);
    }
  }
}
</style> 